<template>
  <div id="mention-modal" :style="{ top: top, left: left }">
    <input id="mention-input" v-model="searchVal" ref="input" @keyup="inputKeyupHandler" />
    <ul id="mention-list">
      <li v-for="item in searchedList" :key="item.id" @click="insertMentionHandler(item.id, item.name)">{{
        item.name
      }}</li>
    </ul>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  const emit = defineEmits(['hideMentionModal', 'insertMention']);
  const top = ref('0px');
  const left = ref('0px');
  const searchVal = ref('');
  const list = ref([
    { id: 'a', name: 'A张三' },
    { id: 'b', name: 'B李四' },
    { id: 'c', name: 'C小明' },
    { id: 'd', name: 'D小李' },
    { id: 'e', name: 'E小红' },
  ]);
  const searchedList = computed(() => {
    const searchValue = searchVal.value.trim().toLowerCase();
    return list.value.filter((item) => {
      const name = item.name.toLowerCase();
      if (name.indexOf(searchValue) >= 0) {
        return true;
      }
      return false;
    });
  });
  const inputKeyupHandler = (event) => {
    // esc - 隐藏 modal
    if (event.key === 'Escape') {
      emit('hideMentionModal');
    }

    // enter - 插入 mention node
    if (event.key === 'Enter') {
      // 插入第一个
      const firstOne = searchedList.value[0];
      if (firstOne) {
        const { id, name } = firstOne;
        insertMentionHandler(id, name);
      }
    }
  };
  const insertMentionHandler = (id, name) => {
    console.log('插入的值:', id, name);
    emit('insertMention', id, name);
    emit('hideMentionModal'); // 隐藏 modal
  };
  onMounted(() => {
    const domSelection = document.getSelection();
    const domRange = domSelection?.getRangeAt(0);
    if (domRange == null) return;
    const rect = domRange.getBoundingClientRect();

    // 定位 modal
    top.value = `${rect.top + 20}px`;
    left.value = `${rect.left + 5}px`;
  });
</script>

<style>
  #mention-modal {
    position: absolute;
    border: 1px solid #ccc;
    background-color: #fff;
    padding: 5px;
  }

  #mention-modal input {
    width: 100px;
    outline: none;
  }

  #mention-modal ul {
    padding: 0;
    margin: 0;
  }

  #mention-modal ul li {
    list-style: none;
    cursor: pointer;
    padding: 3px 0;
    text-align: left;
  }

  #mention-modal ul li:hover {
    text-decoration: underline;
  }
</style>
